package com.gs.synedocket.fragment.docket;

import android.content.Intent;
import android.os.Build;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.gs.synedocket.R;
import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.control.TitleView;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.dto.ConfirmDocketDto;
import com.gs.synedocket.db.dto.DocketAccRepDto;
import com.gs.synedocket.db.dto.DocketAddChargeDto;
import com.gs.synedocket.db.entity.DocketPhoto;
import com.gs.synedocket.db.sqlite.DBApi;
import com.gs.synedocket.dialog.DialogUtil;
import com.gs.synedocket.dialog.LoadingDialogUtils;
import com.gs.synedocket.dialog.SureDialog;
import com.gs.synedocket.dialog.ToastDialogUtils;
import com.gs.synedocket.fragment.base.BaseSignFragment;
import com.gs.synedocket.presenter.DocketOkPresenter;
import com.gs.synedocket.util.DateUtil;
import com.gs.synedocket.util.DocketUtil;
import com.gs.synedocket.util.SPUtil;
import com.gs.synedocket.view.IDocketOkView;

import org.greenrobot.eventbus.EventBus;

import java.util.Date;

public class DocketOkFragment extends BaseSignFragment<IDocketOkView, DocketOkPresenter> implements IDocketOkView {

    private TextView tvArriveSite, tvStart, tvEnd;
    private SureDialog sureDialog;
    private DocketAddChargeDto mBean;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_docket_ok;
    }

    @Override
    protected DocketOkPresenter createPresenter() {
        return new DocketOkPresenter();
    }

    @Override
    protected void initView() {
        TitleView viewOk = fd(R.id.view_ok);
        viewOk.setContent(fd(R.id.ll_ok));
        tvArriveSite = fd(R.id.tv_arrive_site);
        tvStart = fd(R.id.tv_start);
        tvEnd = fd(R.id.tv_end);
        btnUnSign.setText(R.string.not_add_sign);
        btnUnSign.setBackgroundResource(R.drawable.green_bg);
        MyOnClickListener onClickListener = new MyOnClickListener();
        btnUnSign.setOnClickListener(onClickListener);
    }

    @Override
    protected void initData() {
        tvArriveSite.setText(DateUtil.DateTimeToStr(DocketUtil.getInstance().getArriveSiteAt(), "HH:mm"));
        tvStart.setText(DateUtil.DateTimeToStr(DocketUtil.getInstance().getStartDisAt(), "HH:mm"));
        tvEnd.setText(DateUtil.DateTimeToStr(new Date(), "HH:mm"));
    }

    @Override
    public void onUploadFileSuccess(ApiResultData<String> apiResult) {
        if (apiResult.getStatus() != 2000) {
            if (isPhoto) {
                deleteReportPhoto(listReport.size() - 1);
            }
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResult.getMessage());
            hideLoading();
            return;
        }
        if (isPhoto && !listReport.isEmpty()) {
            isPhoto = false;
            listReport.set(listReport.size() - 1, new DocketPhoto(apiResult.getData()));
            hideLoading();
            return;
        }
        if (isTakePhoto) {
            isTakePhoto = false;
            mTakePhoto = apiResult.getData();
            mPresenter.uploadBase64(mSignPhoto, null);
        } else {
            confirm(apiResult.getData());
        }
    }

    @Override
    public void onUploadFileFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
        if (isPhoto) {
            deleteReportPhoto(listReport.size() - 1);
        }
    }

    @Override
    public void onUpdateSuccess(ApiResultData<String> apiResultData) {
        ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
        if (apiResultData.getStatus() != 2000) {
            mBean = null;
            return;
        }
        LogUtil.getInstance().insertOrReplaceData(DocketUtil.getInstance().getDocketNo() + "-確認成功");
        DBApi.getInstance().updateDocketState(mBean.getDocketId(), 2);
        mBean.setState(1);
        DBApi.getInstance().insertNewAddCharge(mBean);
        mBean = null;
        DocketUtil.getInstance().setDriverState(2);
        EventBus.getDefault().post(new Event(EventCode.EVENT_DONE_COMPLETE));
    }

    private void refreshView() {
        mBean = null;
        clear();
    }

    @Override
    public void onUpdateFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
        mBean = null;
    }

    @Override
    public void onWithoutSignSuccess(ApiResultData<String> apiResultData) {
        ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
        if (apiResultData.getStatus() != 2000) {
            mBean = null;
            return;
        }
        mBean = null;
        withoutSignSuccess();
    }

    @Override
    public void onWithoutSignFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
        mBean = null;
    }

    @Override
    public void onAddInfoSuccess(ApiResultData<String> apiResult) {
        addReportSuccess(apiResult);
    }

    @Override
    public void onAddInfoFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(context);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btn_unsigned) {
                if (sureDialog == null) {
                    sureDialog = new SureDialog(context, R.string.unsigned, () -> {
                        ConfirmDocketDto bean = new ConfirmDocketDto();
                        bean.setDocketId(DocketUtil.getInstance().getDocketId());
                        mPresenter.comWithoutSign(bean);
                    });
                }
                sureDialog.show();
            }
        }
    }

    private void confirm(String photo) {
        mBean = new DocketAddChargeDto();
        mBean.setDocketId(DocketUtil.getInstance().getDocketId());
        mBean.setPhoto(photo);
        mBean.setPhoto1(mTakePhoto);
        mPresenter.confirm(mBean);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void confirm() {
        showLoading();
        // 判断需不需要拍照
        if (SPUtil.getInstance().getInt(AllConstants.TAKE_PHOTO,  getResources().getInteger(R.integer.take_photo)) == 1) {
            cameraUtil.takePhoto();
        }else {
            mPresenter.uploadBase64(mSignPhoto, null);
        }
    }

    @Override
    protected void submitReport() {
        showLoading();
        DocketAccRepDto dto = createDto();
        if (dto == null) {
            return;
        }
        mPresenter.addAccRep(dto);
    }

    @Override
    protected void uploadReportPhoto(String url) {
        mPresenter.upload(url);
    }

    @Override
    protected void takePhoto(String url) {
        mPresenter.uploadBase64(url, true);
    }

    @Override
    protected void captureError() {
        hideLoading();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            refreshView();
        } else {
            clearReport();
            initData();
            initReport();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        photoResult(requestCode, resultCode, data);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        photoPermissionsResult(requestCode, grantResults);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DialogUtil.getInstance().dialogDestroy(sureDialog);
    }
}
